package logic

import (
	"context"
	"fmt"
	"hotel/model/RedisInit"
	"hotel/model/mysql"

	"hotel/hotelrpc/hotelrpc"
	"hotel/hotelrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *hotelrpc.UserLoginRequest) (*hotelrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	get := RedisInit.Client.Get("sendSms" + "login" + in.Username)
	if get.Val() != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误")
	}
	var users mysql.User
	mysql.DB.Debug().Where("username = ?", in.Username).Find(&users)
	if users.ID == 0 {
		return nil, fmt.Errorf("账户不存在,请重新输入")
	}
	if users.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}
	RedisInit.Client.Del("sendSms", in.Username)
	return &hotelrpc.UserLoginResponse{
		Id: int64(users.ID),
	}, nil
}
